package com.fingard.dsp.bank.directbank.spdb11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author XueJy on 2018/9/25.
 * @version 1.0
 */
public class SPDB11ScheduleTask extends SPDB11Base implements IScheduleTask {
    @Override
    public void execTask(TaskTimerSet timerSet) {
        try {
            if (timerSet.taskNameList.toLowerCase().contains("autodownfinish")) {
                autoDownFinish();
			}
			if (timerSet.taskNameList.toLowerCase().contains("autouploadothersystem")) {
				autoUploadOtherSystem();
			}
			if (timerSet.taskNameList.toLowerCase().contains("autodownloadothersystem")) {
				autoDownloadOtherSystem();
            }
        } catch (Exception ex) {
            this.WriteBankLogLn(ex);
        }
    }

    public void autoDownFinish() {
        try {
            String isCombineFINISH = getBankConfig().getValueAsString("isCombineFINISH");
            if ("1".equals(isCombineFINISH)) {
                Date tmpDateNow = new Date();
                String tmpDateHour = Format.Time8Format.format(tmpDateNow).substring(0, 5);
                String tmpMinutes = getBankConfig().getValueAsString("taskTimeHourMinutes");
                if (StringHelper.hasAnyChar(tmpMinutes)) {
                    for (String tmpMinite : tmpMinutes.split("\\|\\|")) {
                        if (tmpDateHour.equals(tmpMinite)) {
                            String basePath = getLocalSavePath(new Date());
                            String localSavePath = basePath + File.separator + "FINISH_BAK";
                            int maxBatch = 0;
                            File dataFileDir = new File(localSavePath);
                            if (dataFileDir.exists()) {
                                int len = dataFileDir.listFiles().length;
                                if (len > 0) {
                                    maxBatch = len + 1;
                                } else {
                                    maxBatch = 1;
                                }
                            } else {
                                dataFileDir.mkdirs();
                                maxBatch = 1;
                            }
                            String backup = localSavePath + File.separator + "FINISH_" + String.format("%3s", maxBatch).replace(" ", "0");
                            //ftp下载 客户处的 FINISH文件
                            FtpSet ftpSet = bankFront.getFtpSet("finish");
                            FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                            WriteBankLogLn("下载FINISH地址:" + ftpSet.serverIP + ":" + ftpSet.port + File.separator + ftpSet.downDir);
                            FtpReceiver ftpReceiver = ftpPtClient.downloadFile("FINISH", backup);
                            if (ftpReceiver.isCompleted) {
                                WriteBankLogLn("下载FINISH文件成功");

                            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                                WriteBankLogLn("下载FINISH文件时，通讯失败");
                            } else {
                                WriteBankLogLn(ftpReceiver.connMsg);
                            }

                            String locFinishPath = basePath + File.separator + "FINISH_LOCAL";
                            String finishPath = basePath + File.separator + "FINISH";
                            StringBuilder sb = new StringBuilder();
                            String localcontent = FileHelper.readFileText(locFinishPath, getCharset());
                            String remotecontent = FileHelper.readFileText(backup, getCharset());
                            //合并FINISH
                            if (localcontent != null && !"".equals(localcontent)) {
                                sb.append(localcontent.replace("finish", ""));
                            }
                            if (remotecontent != null && !"".equals(remotecontent)) {
                                sb.append(remotecontent.replace("finish", ""));
                            }
                            sb.append("finish");
                            FileHelper.writeFile(finishPath, sb.toString(), getCharset());
                            String[] res = upFileToBank(finishPath);
                            if (res[0].length() == 0) {
                                WriteBankLogLn("成功上传合并后FINISH文件");
                            } else {
                                WriteBankLogLn("FINISH文件上传失败");
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            WriteBankLogLn(ex);
        }
    }

	public void autoUploadOtherSystem() {
		try {
			Date tmpDateNow = new Date();
			String tmpDateHour = Format.Time8Format.format(tmpDateNow).substring(0, 5);
			String tmpMinutes = getBankConfig().getValueAsString("taskTimeHourMinutesOtherSystem");
			if (StringHelper.hasAnyChar(tmpMinutes)) {
				for (String tmpMinite : tmpMinutes.split("\\|\\|")) {
					if (tmpDateHour.equals(tmpMinite)) {
						String basePath = getLocalSavePath(new Date());
						String localSavePath = basePath + File.separator + "YBT_BACK";
						WriteBankLogLn("银保通文件保存目录：" + localSavePath);
						// ftp下载 银保通的 文件
						FtpSet ftpSet = bankFront.getFtpSet("othersystem");
						FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
						WriteBankLogLn("下载其他系统文件的FTP地址:" + ftpSet.serverIP + ":" + ftpSet.port + File.separator + ftpSet.downDir);
						ftpPtClient.connect();
						ftpPtClient.list(ftpSet.downDir, false);
						ArrayList<String> ftpFileList = ftpPtClient.arFiles;
						for (int i = 0; i < ftpFileList.size(); i++) {
							String ftpFileName = ftpFileList.get(i);
							if ( ftpFileName.contains(".TXT") && ftpFileName.contains("UBS")) {
								// 下载并保存到本地
								FtpReceiver tmpReceiver = ftpPtClient.downloadFile(ftpFileName,
										localSavePath + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length()));
								if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
									// 上送浦发
									File file = new File(localSavePath + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length()));
									String tmpReqData = FileHelper.readToString(file, "UTF-8");
									String[] upFinishRet = sendToBank(tmpReqData, tmpDateNow,
											ftpFileName.substring(ftpFileName.lastIndexOf("/") + 1, ftpFileName.length()), "UBS");
									if (upFinishRet[0].length() == 0) {
										// 上送成功后转储
										String p_localFile = localSavePath + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length());
										String p_trgFileName = getBankConfig().getValueAsString("othersystembackupdir") + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length());
										WriteBankLogLn("本地文件文件：" + p_localFile);
										WriteBankLogLn("备份文件文件：" + p_trgFileName);
										ftpPtClient.uploadFile(p_localFile, p_trgFileName);
										ftpPtClient.deleteFile(ftpFileName);
										WriteBankLogLn("上送浦发成功后转储文件：" + ftpFileName);
									} else {
										WriteBankLogLn("上送浦发失败");
										continue;

									}

								}
							}
						}
					}
				}
			}

		} catch (Exception ex) {
			WriteBankLogLn(ex);
		}
	}

	public void autoDownloadOtherSystem() {
		try {
			String transMode = getBankConfig().getValueAsString("transMode");
			Date tmpDateNow = new Date();
			boolean isMatched = false;

			String tmpDateHour = Format.Time8Format.format(tmpDateNow).substring(0, 5);
			String tmpMinutes = getBankConfig().getValueAsString("taskTimeHourMinutesOtherSystemDownload");
			if (StringHelper.hasAnyChar(tmpMinutes)) {
				for (String tmpMinite : tmpMinutes.split("\\|\\|")) {
					if (tmpDateHour.equals(tmpMinite)) {

						// WTP方式请求
						if ("WTP".equals(transMode)) {
							// 状态码, tmpStrQueryResp
							String[] tmpEndRet = downFileFromBank("END", tmpDateNow);
							if (tmpEndRet[0].length() == 0) {
								String tmpEndRespPath = getLocalSavePath(tmpDateNow) + File.separator + "END";
								WriteBankLogLn2("END文件路径：" + tmpEndRespPath);
								String tmpEndFileContent = FileHelper.readFileText(tmpEndRespPath, getCharset());
								WriteBankLogLn2("返回END文件内容:" + tmpEndFileContent);

								String[] tmpFileResp = tmpEndFileContent.split("\n");

								for (String fileName : tmpFileResp) {
									if (fileName.contains("end")) {
										continue;
									}
									if (!fileName.equals("DBS")) {

										isMatched = true;

										String[] tmpDownStrRet = downFileFromBank(fileName, tmpDateNow);
										if (tmpDownStrRet[0].length() == 0) {

											String tmpDownFilePath = getLocalSavePath(tmpDateNow) + File.separator + fileName;
											WriteBankLogLn2("批量同步结果文件路径：" + tmpDownFilePath);
											String tmpStrQueryResp = FileHelper.readFileText(tmpDownFilePath, getCharset());
											WriteBankLogStep3("批量文件内容：" + tmpStrQueryResp);
											if (StringHelper.isNullOrEmpty(tmpStrQueryResp)) {

											} else {
												FtpSet ftpSet = bankFront.getFtpSet("othersystem");
												FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
												WriteBankLogLn("下载其他系统文件的FTP地址:" + ftpSet.serverIP + ":" + ftpSet.port + File.separator + ftpSet.upDir);
												ftpPtClient.connect();
												FtpReceiver tmpReceiver = ftpPtClient.uploadFile(tmpDownFilePath, ftpSet.upDir + fileName);
												if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
													WriteBankLogLn("文件" + fileName + "上传到银保通FTP服务器成功");
												} else {
													WriteBankLogLn("文件" + fileName + "上传到银保通FTP服务器失败，原因：" + tmpReceiver.connMsg);
												}

											}
										} else {
											WriteBankLogLn("从WTP下载" + fileName + "文件失败，原因：" + tmpDownStrRet[1]);

										}
									}
								}
							}
							if (!isMatched) {
								// 下载FAIL文件
								String[] tmpFailStrRet = downFileFromBank("FAIL", tmpDateNow);
								if (tmpFailStrRet[0].length() == 0) {
									// String tmpFailFilePath =
									// StringHelper.trimEnd(bankFront.bkTransFolder,
									// File.separator) + File.separator +
									// "FAIL";
									String tmpFailFilePath = getLocalSavePath(tmpDateNow) + File.separator + "FAIL";
									WriteBankLogLn2("本地代收付FAIL文件路径：" + tmpFailFilePath);
									String tmpFailQueryResp = FileHelper.readFileText(tmpFailFilePath, getCharset());
									WriteBankLogStep3(tmpFailQueryResp);
									String[] failFileArr = tmpFailQueryResp.split("\n");
									for (String failStr : failFileArr) {
										if (failStr.equals("DBS")) {
											WriteBankLogLn("文件：" + failStr + "浦发处理失败");
										}
									}
								} else {
									WriteBankLogLn("从WTP下载FAIL文件失败，原因：" + tmpFailStrRet[1]);
								}
							}

						}
					}
				}
			}
		} catch (Exception ex) {
			WriteBankLogLn(ex);
		}
	}
}
